import { InboxOutlined, PlusOutlined } from '@ant-design/icons';
import { Image, message, Upload } from 'antd';
import { memo, useState } from 'react';
/**
 * <BasicUpload files={files} onChange={setFiles} multiple maxCount={3} />
 */

const dragChildren = ({ drag }) => {
	if (!drag) {
		return '+ Upload';
	}
	return (
		<>
			<p className="ant-upload-drag-icon">
				<PlusOutlined />
			</p>
			<p className="ant-upload-text">点击或拖拽文件到此处上传</p>
		</>
	);
};
const BasicUpload = ({
	files = [],
	onChange = () => {},
	maxCount = 5,
	accept = 'image/*',
	listType = 'picture-card',
	drag = false, // 新增drag属性
	maxSize = 2, // 新增maxSize属性，单位MB
	children = dragChildren(drag),
	...props
}) => {
	const [previewOpen, setPreviewOpen] = useState(false);
	const [previewImage, setPreviewImage] = useState('');

	const customRequest = async (options) => {
		const { file, _onProgress, onSuccess, onError } = options;

		try {
			const res = await new Promise((resolve) => {
				setTimeout(() => {
					if (Math.random() > 0.5) {
						resolve({
							code: 200,
							data: {
								url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100',
								uid: file.uid,
								name: file.name,
							},
						});
					} else {
						resolve({
							code: 500,
							message: '上传失败',
						});
					}
				}, 1000);
			});
			console.log('res', res);

			if (res.code == 200) {
				onSuccess(res.data);
				onChange((pre) => [...pre, res.data]);
			} else {
				onError(res.message || '上传失败');
				message.error(res.message || '上传失败');
			}
		} catch (error) {
			onError(error);
			message.error(error.message || '上传失败');
		}
	};

	// 上传前校验
	const beforeUpload = (file) => {
		const isImage = file.type.startsWith('image/');
		const isLtSize = file.size / 1024 / 1024 < maxSize;
		if (!isImage) {
			message.error('只能上传图片文件!');
			return false;
		}
		if (!isLtSize) {
			message.error(`图片大小不能超过 ${maxSize}MB!`);
			return false;
		}
		return true;
	};
	// 上传文件变化
	const handleChange = ({ /*  file, */ fileList: list }) => {
		console.log('onChange', list);
	};

	// 删除文件
	const onRemove = (file) => {
		onChange?.((pre) => pre.filter((item) => item.uid !== file.uid));
	};

	// 预览文件
	const onPreview = async (file) => {
		setPreviewImage(file.url || file.preview);
		setPreviewOpen(true);
	};

	if (drag) {
		return (
			<Upload.Dragger
				fileList={files}
				accept={accept}
				maxCount={maxCount}
				onChange={handleChange}
				onPreview={onPreview}
				onRemove={onRemove}
				beforeUpload={beforeUpload}
				customRequest={customRequest}
				{...props}
			>
				{children}
			</Upload.Dragger>
		);
	}
	return (
		<>
			<Upload
				listType={listType}
				fileList={files}
				accept={accept}
				maxCount={maxCount}
				onChange={handleChange}
				onPreview={onPreview}
				onRemove={onRemove}
				beforeUpload={beforeUpload}
				customRequest={customRequest}
				{...props}
			>
				{files.length < maxCount && children}
			</Upload>
			{previewImage && (
				<Image
					wrapperStyle={{ display: 'none' }}
					preview={{
						visible: previewOpen,
						onVisibleChange: (visible) => setPreviewOpen(visible),
						afterOpenChange: (visible) => !visible && setPreviewImage(''),
					}}
					src={previewImage}
				/>
			)}
		</>
	);
};

export default memo(BasicUpload);
